package com.example.bnuzzu.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bnuzzu.common.dto.LoginDto;
import com.example.bnuzzu.common.lang.Result;
import com.example.bnuzzu.entity.Houseinfo;
import com.example.bnuzzu.entity.Userimage;
import com.example.bnuzzu.entity.Userinfo;
import com.example.bnuzzu.mapper.UserimageMapper;
import com.example.bnuzzu.mapper.UserinfoMapper;
import com.example.bnuzzu.service.UserimageService;
import com.example.bnuzzu.service.UserinfoService;
import com.example.bnuzzu.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 负责登录的Controller
 *
 *         需要登录查看的页面添加以下注释可以开启shiro验证
 *         @ @RequiresAuthentication
 * @author Corn
 */
@RestController
public class AccountController {

    @Autowired
    UserinfoService userService;
    @Autowired
    UserimageService userimageService;
    @Autowired
    private UserinfoMapper userMapper;
    @Autowired
    private UserimageMapper userimageMapper;
    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto, HttpServletResponse response){

        try{
            Userinfo user=userService.getOne(new QueryWrapper<Userinfo>().eq("username",loginDto.getUsername()));
            Assert.notNull(user,"账号不存在或已冻结");

            if(user.getState() == 1){
                return Result.fail(221,"账号已冻结",null);
            }

            if(!user.getPassword().equals( SecureUtil.md5(loginDto.getPassword()) )){
                return Result.fail(201,"账号或密码有误",null);
            }

            //登陆成功 添加token返回
            String jwt = jwtUtils.generateToken(user.getUserid());

            response.addHeader("Authorization",jwt);
            response.addHeader("Access-control-Expose-Headers","Authorization");

            Map<String,String> map = new LinkedHashMap<>();
            map.put("username",user.getUsername());
            map.put("id",user.getUserid().toString());
            map.put("email",user.getEmail());
            map.put("phone",user.getPhone());

            return Result.success(map);
        }catch (Exception e){
            return Result.fail(502,e.getMessage(),null);
        }
    }


    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@RequestBody Userinfo userinfo){
        QueryWrapper<Userinfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("username",userinfo.getUsername());
        Integer countname = userMapper.selectCount(wrapper1);
        if(countname>=1) {
            return Result.fail(520, "该用户名已存在", null);
        }
        QueryWrapper<Userinfo> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("email",userinfo.getEmail());
        Integer countemail = userMapper.selectCount(wrapper2);
        if(countemail>=1) {
            return Result.fail(521, "该邮箱已存在", null);
        }
        QueryWrapper<Userinfo> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("phone",userinfo.getPhone());
        Integer countphone = userMapper.selectCount(wrapper3);
        if(countphone>=1) {
            return Result.fail(522, "该号码已存在", null);
        }
        String username =userinfo.getUsername();
        userinfo.setUsername(username);
        String password =userinfo.getPassword();
        userinfo.setPassword(SecureUtil.md5(password));
        String email =userinfo.getEmail();
        userinfo.setEmail(email);
        String phone =userinfo.getPhone();
        userinfo.setPhone(phone);
        Integer age =userinfo.getAge();
        userinfo.setAge(age);
        userService.save(userinfo);

        Userimage userimage = new Userimage();
        userimage.setUserimage("default.jpeg");
        userimage.setUserid(userinfo.getUserid());
        userimageMapper.insert(userimage);

        return Result.success(null);
    }


    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }
}
